from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from django.urls import reverse
from .qidian import *
from .spider import Spider
# Create your views here.
def index(request):
    info = Novel().free_info
    context = {'info':info}
    
    return render(request,'qidian/index.html',context)
def novel_info(request,book_id):
    novel_url = 'https://book.qidian.com/info/{}#Catalog'.format(book_id)
    novel_html = Spider(novel_url).html
    
    name = ' <title>《(.*?)》_(.*?)_.*?_起点中文网</title>'
    
    chapter_re = '<a href="//read.qidian.com/chapter/(.*?)" target="_blank" data-eid="qd_G55" data-cid=".*?" title=".*?">(.*?)</a>'
    name = re.findall(name,novel_html)
    chapter_info = re.findall(chapter_re,novel_html)
    context = {'name_info':name,
               'chapter_info':chapter_info}
    
    return render(request,'qidian/look.html',context)
    
def chapter_info(request):
    chapter_id = request.GET['chapter_id']
    chapter_url = 'https://read.qidian.com/chapter/{}'.format(chapter_id)
    
    chapter_html = Spider(chapter_url).html
    
    chapter_content = '<div class="read-content j_readContent">(.*?)</div>'
    chapter_up = '<a id="j_chapterPrev" data-eid="qd_R107" href="//read.qidian.com/chapter/(.*?)">.*?</a>'
    chapter_menu = '<a href="//book.qidian.com/info/(.*?)#Catalog" target="_blank" data-eid="qd_R108">.*?</a>'
    chapter_down = '<a id="j_chapterNext" href="//read.qidian.com/chapter/(.*?)" data-eid="qd_R109">.*?</a>'
    chapter_content = re.findall(chapter_content,chapter_html,re.S)
    chapter_up = re.findall(chapter_up,chapter_html)
    chapter_menu = re.findall(chapter_menu,chapter_html)
    chapter_down = re.findall(chapter_down,chapter_html)
    
    context = {'content':chapter_content,
               'chapter_up':chapter_up,
               'chapter_menu':chapter_menu,
               'chapter_down':chapter_down
               }
    print(context)
    return render(request,'qidian/chapter.html',context)
